<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();
const loading = ref(false);
const records = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const tableData = ref([]);

// Dialog control
const dialogVisible = ref(false);
const currentRecord = ref(null);

onMounted(() => {
  fetchRecords();
});

// Fetch analysis records
const fetchRecords = async () => {
  loading.value = true;
  
  try {
    // API call
    const response = await axios.get('/api/admin/analysis/records', {
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    });
    
    if (response.data.code === 200 || response.data.code === '200') {
      records.value = response.data.data.records || response.data.data;
      total.value = response.data.data.total || records.value.length;
      handleTableData();
      ElMessage.success('获取分析记录成功');
    } else {
      ElMessage.error('获取分析记录失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error('获取分析记录失败:', error);
    ElMessage.error('获取分析记录失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// Handle table data display
const handleTableData = () => {
  tableData.value = records.value.map(record => ({
    ...record,
    // Format dates to be more readable
    startTime: formatDateTime(record.startTime),
    endTime: formatDateTime(record.endTime)
  }));
};

// Format date time for display
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  
  try {
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit', 
      minute: '2-digit'
    });
  } catch (e) {
    return dateTimeStr;
  }
};

// Handle page change
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchRecords();
};

// View record details - fetches detailed data from API
const viewRecordDetails = (record) => {
  currentRecord.value = record;
  dialogVisible.value = true;
};
</script>

<template>
  <div>
    <div class="classroom-records">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>课堂分析记录</span>
            
            <el-button 
              type="primary" 
              size="small" 
              style="margin-left: 20px;"
              @click="$router.push('/tabus/classroom-analysis')"
            >
              返回课堂分析
            </el-button>
          </div>
        </template>
        
        <!-- Records Table -->
        <div class="records-table">
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            border
            stripe
            highlight-current-row
          >
            <el-table-column
              prop="teacher"
              label="教师"
              align="center"
              width="90"
            />
            <el-table-column
              prop="className"
              label="班级"
              align="center"
              width="110"
            />
            <el-table-column
              prop="courseName"
              label="课程名称"
              align="center"
            />
            <el-table-column
              prop="studentRaiseRate"
              label="学生抬头率(%)"
              width="140"
              align="center"
            >
              <template #default="scope">
                <span>{{ scope.row.studentRaiseRate ? scope.row.studentRaiseRate.toFixed(1) : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="studentLowerRate"
              label="学生低头率(%)"
              width="140"
              align="center"
            >
              <template #default="scope">
                <span>{{ scope.row.studentLowerRate ? scope.row.studentLowerRate.toFixed(1) : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="teacherHappinessAvg"
              label="教师快乐平均值"
              width="140"
              align="center"
            >
              <template #default="scope">
                <span>{{ scope.row.teacherHappinessAvg ? scope.row.teacherHappinessAvg.toFixed(1) : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="teacherAngerAvg"
              label="教师生气平均值"
              width="140"
              align="center"
            >
              <template #default="scope">
                <span>{{ scope.row.teacherAngerAvg ? scope.row.teacherAngerAvg.toFixed(1) : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="teacherNeutralAvg"
              label="教师中性平均值"
              width="140"
              align="center"
            >
              <template #default="scope">
                <span>{{ scope.row.teacherNeutralAvg ? scope.row.teacherNeutralAvg.toFixed(1) : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
            >
              <template #default="scope">
                <div class="action-btn-group">
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="viewRecordDetails(scope.row)"
                  >
                    查看详情
                  </el-button>
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="$router.push({path: '/tabus/classroom-feedback', query: {recordId: scope.row.courseId}})"
                  >
                    课程反馈与建议
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- Pagination -->
          <div class="pagination-container">
            <el-pagination
              v-if="total > pageSize"
              :current-page="currentPage"
              :page-size="pageSize"
              :total="total"
              layout="total, prev, pager, next"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-card>
    </div>

    <!-- Detail Dialog -->
    <el-dialog
      title="课堂分析详情"
      v-model="dialogVisible"
      width="800px"
    >
      <div v-if="currentRecord" class="record-details">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="课程ID">{{ currentRecord.courseId }}</el-descriptions-item>
          <el-descriptions-item label="教师">{{ currentRecord.teacher }}</el-descriptions-item>
          <el-descriptions-item label="课程名称">{{ currentRecord.courseName }}</el-descriptions-item>
          <el-descriptions-item label="班级">{{ currentRecord.className }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ currentRecord.startTime }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ currentRecord.endTime }}</el-descriptions-item>
          <el-descriptions-item label="学生抬头率(%)">
            {{ currentRecord.studentRaiseRate ? currentRecord.studentRaiseRate.toFixed(1) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="学生低头率(%)">
            {{ currentRecord.studentLowerRate ? currentRecord.studentLowerRate.toFixed(1) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="教师快乐平均值">
            {{ currentRecord.teacherHappinessAvg ? currentRecord.teacherHappinessAvg.toFixed(1) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="教师生气平均值">
            {{ currentRecord.teacherAngerAvg ? currentRecord.teacherAngerAvg.toFixed(1) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="教师中性平均值">
            {{ currentRecord.teacherNeutralAvg ? currentRecord.teacherNeutralAvg.toFixed(1) : '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.classroom-records {
  max-width: 1400px;
  margin: 0 auto;
  padding-top: 20px;
}

.card-header {
  display: flex;
  align-items: center;
}

.records-table {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.record-details {
  padding: 10px;
}

:deep(.el-table .el-table__row:hover) {
  cursor: pointer;
}

.action-btn-group {
  display: flex;
  flex-direction: row;
  gap: 8px;
  justify-content: center;
  align-items: center;
}
</style> 